package com.feige.utils.validate;

import com.feige.constant.Constants;
import com.feige.utils.exception.user.CaptchaException;
import com.feige.utils.exception.user.CaptchaExpireException;
import com.feige.utils.redis.RedisUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author feige<br />
 * @ClassName: ValidateEmail <br/>
 * @Description: 验证邮箱验证码<br/>
 * @date: 2021/4/22 16:48<br/>
 */
@Component
public class ValidateEmail {
    @Resource
    private RedisUtils redisUtils;


    public void validateEmail(String email, String code) {
        String key = Constants.EMAIL_CODE_KEY + email;
        getVerifyCode(key,code);
    }

    /**
     * 获取验证码
     * @param key
     * @param code
     */
    public void getVerifyCode(String key,String code){
        //获取验证码
        String redisCode = (String) redisUtils.get(key);
        if (StringUtils.isEmpty(redisCode)){
            throw new CaptchaExpireException();
        }
        //删除验证码
        redisUtils.del(key);
        if (!code.equalsIgnoreCase(redisCode)){
            throw new CaptchaException();
        }
    }
}
